package concurrent.result;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class ResultByFutureTask {
    public static void main(String[] args) throws ExecutionException, InterruptedException, ExecutionException {
        System.out.println(System.currentTimeMillis());
        //创建一个FutureTask
        FutureTask<Integer> futureTask = new FutureTask<>(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 10;
        });
        //将futureTask传递一个线程运行
        new Thread(futureTask).start();
        System.out.println(System.currentTimeMillis());
        //futureTask.get()会阻塞当前线程，直到futureTask执行完毕
        Integer result = futureTask.get();
        System.out.println(System.currentTimeMillis() + ":" + result);


        //================第二种方式,在方法内定义futureTask2 然后在线程内去执行run方法，用的比较少================
        FutureTask<Integer> futureTask2 = new FutureTask<>(() -> 10);
        //将futureTask传递一个线程运行
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            futureTask2.run();
        }).start();
        Integer result2 = futureTask2.get();
        System.out.println(System.currentTimeMillis() + ":" + result2);
        //总结：需要整合数据的时候，可能需要多个futureTask,因此引入了CompletableFuture
    }
}
